/* eslint-disable */

import MiniProgram from 'miniprogram-automator/out/MiniProgram'

import { IAnyObject, MiniProgramReport, MiniProgramSendEvent } from '@slardar/sdk-mini-program'

import { matchFuzzily } from './helper'

type RecursivePartial<T> = {
  [P in keyof T]?: T[P] extends (infer U)[]
    ? RecursivePartial<U>[]
    : T[P] extends IAnyObject
    ? RecursivePartial<T[P]>
    : T[P]
}

export const getSendStack = async (miniProgram: MiniProgram) => {
  return miniProgram.evaluate(() => {
    return (wx as any).sendStack as MiniProgramSendEvent
  })
}

export const getReportStack = async (miniProgram: MiniProgram) => {
  return miniProgram.evaluate(() => {
    return (wx as any).reportStack as MiniProgramReport
  })
}

export const matchFuzzilyWithSendStack = async (miniProgram: MiniProgram, findObj: Partial<MiniProgramSendEvent>) => {
  const stack = await getSendStack(miniProgram)
  return matchFuzzily(stack, findObj) as MiniProgramSendEvent[]
}

export const findFuzzilyWithSendStack = async (
  miniProgram: MiniProgram,
  findObj: Partial<MiniProgramSendEvent>,
  index = 0,
) => {
  const res = await matchFuzzilyWithSendStack(miniProgram, findObj)
  return res[index]
}

export const matchFuzzilyWithReportStack = async (
  miniProgram: MiniProgram,
  findObj: RecursivePartial<MiniProgramReport>,
) => {
  const stack = await getReportStack(miniProgram)
  return matchFuzzily(stack, findObj) as MiniProgramReport[]
}

export const findFuzzilyWithReportStack = async (
  miniProgram: MiniProgram,
  findObj: RecursivePartial<MiniProgramReport>,
  index = 0,
) => {
  const res = await matchFuzzilyWithReportStack(miniProgram, findObj)
  return res[index]
}
